package com.fenghongzhang.lib_dialog.view

import android.animation.Animator
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.util.AttributeSet
import android.view.View
import android.view.animation.LinearInterpolator

/**
 * 自定义圆形进度条View
 * 功能：显示圆形进度，支持开始、暂停、继续等操作
 */
class CircleProgressView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    // 画笔对象，用于绘制所有图形
    private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        style = Paint.Style.STROKE          // 设置为描边模式
        strokeWidth = 20f                   // 设置线条宽度
        strokeCap = Paint.Cap.ROUND         // 设置线条端点为圆形
        textAlign = Paint.Align.CENTER      // 文字居中对齐
        textSize = 40f                      // 设置文字大小
    }

    // 用于存储圆形的矩形范围
    private val rect = RectF()

    // 当前进度值（0f-1f）
    private var progress = 0f

    // 是否完成状态
    private var isCompleted = false

    // 动画控制器
    private var animator: ValueAnimator? = null

    // 加载完成的回调
    var onLoadingFinished: (() -> Unit)? = null

    // 判断是否正在加载
    fun isLoading() = animator?.isRunning == true

    // 判断是否处于暂停状态
    fun isPaused() = animator?.isPaused == true

    // 获取当前加载状态
    fun getState(): LoadingState = when {
        isPaused() -> LoadingState.PAUSED
        isLoading() -> LoadingState.LOADING
        else -> LoadingState.IDLE
    }

    /**
     * 当View大小改变时调用
     * 用于计算圆形的绘制范围
     */
    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        val padding = paint.strokeWidth / 2
        rect.set(padding, padding, w - padding, h - padding)
    }

    /**
     * View的绘制方法
     * 负责绘制背景圆、进度圆弧和中心文字
     */
    override fun onDraw(canvas: Canvas) {
        with(paint) {
            // 1. 绘制背景圆
            style = Paint.Style.STROKE
            color = Color.LTGRAY
            canvas.drawCircle(width/2f, height/2f, width/2f - strokeWidth/2, this)

            // 2. 绘制进度圆弧
            color = if (isCompleted) Color.GREEN else Color.BLUE
            canvas.drawArc(rect, -90f, progress * 360f, false, this)

            // 3. 绘制中心文字
            style = Paint.Style.FILL
            color = if (isCompleted) Color.GREEN else Color.BLACK
            canvas.drawText(
                if (isCompleted) "完成" else "${(progress * 100).toInt()}%",
                width/2f,
                height/2f + (descent() - ascent())/4,  // 文字垂直居中的计算
                this
            )
        }
    }

    /**
     * 切换加载状态
     * 根据当前状态决定是开始、暂停还是继续
     */
    fun toggleLoading() {
        when (getState()) {
            LoadingState.LOADING -> pauseLoading()
            LoadingState.PAUSED -> resumeLoading()
            LoadingState.IDLE -> startLoading()
        }
    }

    /**
     * 开始加载
     * 创建并启动动画，从0到1进行10秒的平滑过渡
     */
    private fun startLoading() {
        isCompleted = false
        progress = 0f
        animator?.cancel()
        animator = ValueAnimator.ofFloat(0f, 1f).apply {
            duration = 5000                     // 动画持续10秒
            interpolator = LinearInterpolator()  // 使用线性插值器，确保匀速运动
            addUpdateListener {
                progress = it.animatedValue as Float
                invalidate()                     // 更新进度后重绘
            }
            addListener(object : Animator.AnimatorListener {
                override fun onAnimationStart(animation: Animator) {}
                override fun onAnimationEnd(animation: Animator) {
                    isCompleted = true          // 设置完成状态
                    invalidate()                // 重绘显示完成状态
                    onLoadingFinished?.invoke() // 调用完成回调
                }
                override fun onAnimationCancel(animation: Animator) {}
                override fun onAnimationRepeat(animation: Animator) {}
            })
            start()
        }
    }

    // 暂停加载
    private fun pauseLoading() = animator?.pause()

    // 继续加载
    private fun resumeLoading() = animator?.resume()

    // 定义加载状态枚举
    enum class LoadingState {
        IDLE,       // 空闲状态
        LOADING,    // 加载中
        PAUSED      // 已暂停
    }
}